package ExcelUtils;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @BelongsProject: Utils
 * @BelongsPackage: ExcelUtils
 * @Author: gejingyu
 * @Date: 2024/1/14
 * @Description: Excel表格导出数据工具
 */

public class ExportUtil {

    /**
     * 导出数据到Excel表格
     *
     * @param tableItem 第一行表头名称
     * @param data      导出数据
     * @param xlsxPath  Excel文件路径
     */
    public static void exportWorkBook(List<String> tableItem, List<Map<String, String>> data, String xlsxPath) {

        //创建工作簿对象
        Workbook workbook = new XSSFWorkbook();

        //创建sheet对象
        Sheet sheet = workbook.createSheet();
        //设置表头
        Row hearderRow = sheet.createRow(0);
        for (int i = 0; i < tableItem.size(); i++) {
            Cell cell = hearderRow.createCell(i);
            cell.setCellValue(tableItem.get(i));
        }

        //写入每行数据
        for (int i = 0; i < data.size(); i++) {
            Row row = sheet.createRow(i + 1);
            Map<String, String> dataMap = data.get(i);
            //循环该行数据，创建每一列，根据列数获取列名并获取对应字段值
            for (int cellNum = 0; cellNum < dataMap.size(); cellNum++) {
                Cell cell = row.createCell(cellNum);
                String res = dataMap.get(tableItem.get(cellNum));
                cell.setCellValue(res);
            }
        }

        try {
            FileOutputStream outputStream = new FileOutputStream(xlsxPath);
            workbook.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
